
<!-- 在模板中添加删除功能 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧商品类型树形列表 -->
      <el-col :span="6">
        <div class="category-tree-container">
          <div class="header">
            <h3>商品类型</h3>
            <!-- 添加新增一级类目按钮 -->
            <el-button type="primary" size="small" @click="handleAddRootCategory">新增一级类目</el-button>
          </div>

          <!-- 添加搜索框 -->
          <div class="search-box">
            <el-input
                v-model="searchKeyword"
                placeholder="请输入类目名称搜索"
                clearable
                @clear="handleSearch"
                @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button :icon="Search" @click="handleSearch" />
              </template>
            </el-input>
          </div>

          <el-tree
              ref="categoryTreeRef"
              :data="categoryTreeData"
              node-key="id"
              :props="defaultProps"
              :expand-on-click-node="false"
              :default-expanded-keys="defaultExpandedKeys"
              @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <!-- 为一级类目添加操作按钮 -->
                <span v-if="data.parentId === 0">
                  <el-button type="primary" link size="small" @click.stop="handleAddChildCategory(data)">添加子类目</el-button>
                  <el-button type="danger" link size="small" @click.stop="handleDeleteCategory(data)">删除</el-button>
                </span>
                <!-- 为二级类目添加删除按钮 -->
                <span v-else>
                  <el-button type="danger" link size="small" @click.stop="handleDeleteCategory(data)">删除</el-button>
                </span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-col>

      <!-- 右侧详情区域 -->
      <el-col :span="18">
        <div class="category-detail-container">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>{{ selectedCategory ? selectedCategory.categoryName : '商品类型详情' }}</span>
              </div>
            </template>
            <div v-if="selectedCategory" class="category-info">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="类目名称">{{ selectedCategory.categoryName }}</el-descriptions-item>
                <el-descriptions-item label="类目详情">
                  <el-tag :type="selectedCategory.parentId === 0 ? 'primary' : 'success'">
                    {{ selectedCategory.parentId === 0 ? '一级类目' : '二级类目' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="排序">{{ selectedCategory.sortOrder }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                  <el-tag :type="selectedCategory.isEnabled === 1 ? 'success' : 'danger'">
                    {{ selectedCategory.isEnabled === 1 ? '启用' : '禁用' }}
                  </el-tag>
                </el-descriptions-item>
              </el-descriptions>

              <!-- 添加操作按钮 -->
              <div class="category-actions" style="margin-top: 20px;">
                <el-button v-if="selectedCategory.parentId === 0" type="primary" @click="handleAddChildCategory(selectedCategory)">
                  添加子类目
                </el-button>
                <el-button type="primary" @click="handleEditCategory(selectedCategory)">
                  编辑类目
                </el-button>
                <el-button type="danger" @click="handleDeleteCategory(selectedCategory)">
                  删除类目
                </el-button>
              </div>
            </div>
            <div v-else class="empty-placeholder">
              <el-empty description="请选择左侧类目查看详细信息" />
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>

  <!-- 类目数据表格 -->
  <div class="category-table-container">
    <div class="table-header">
      <h3>{{ selectedCategory ? selectedCategory.categoryName + ' - 子类目列表' : '子类目列表' }}</h3>
    </div>

    <!-- 数据表格 -->
    <el-table
        :data="subcategoryList"
        border
        stripe        style="width: 100%"
        v-loading="loading"
    >
      <el-table-column prop="categoryName" label="类目名称" show-overflow-tooltip />
      <el-table-column label="类目详情">
        <template #default="scope">
          <el-tag :type="scope.row.parentId === 0 ? 'primary' : 'success'">
            {{ scope.row.parentId === 0 ? '一级类目' : '二级类目' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sortOrder" label="排序" width="100" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isEnabled === 1 ? 'success' : 'danger'">
            {{ scope.row.isEnabled === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button type="primary" link @click="handleEditCategory(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDeleteCategory(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="queryForm.pageNum"
        v-model:page-size="queryForm.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <!-- 新增/编辑类目对话框 -->
  <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      append-to-body
  >
    <el-form
        :model="categoryForm"
        :rules="formRules"
        ref="categoryFormRef"
        label-width="100px"
    >
      <el-form-item label="类目名称" prop="categoryName">
        <el-input v-model="categoryForm.categoryName" placeholder="请输入类目名称" />
      </el-form-item>
      <el-form-item label="父级类目" prop="parentId">
        <el-select
            v-model="categoryForm.parentId"
            placeholder="请选择父级类目"            style="width: 100%"
            :disabled="isEdit && selectedCategory && selectedCategory.parentId === 0"
        >
          <el-option label="一级类目" :value="0" />
          <el-option
              v-for="category in firstLevelCategories"
              :key="category.id"
              :label="category.categoryName"
              :value="parseInt(category.id)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sortOrder">
        <el-input-number v-model="categoryForm.sortOrder" :min="0" controls-position="right" style="width: 100%" />
      </el-form-item>
      <el-form-item label="状态" prop="isEnabled">
        <el-radio-group v-model="categoryForm.isEnabled">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>import { ref, onMounted, nextTick, computed } from 'vue'
import api from '@/utils/request.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

// 数据相关
const categoryTreeData = ref([])
const defaultExpandedKeys = ref([])
const selectedCategory = ref(null)
const subcategoryList = ref([])
const originalCategoryData = ref([]) // 保存原始完整数据

// 搜索相关
const searchKeyword = ref('')

// 表单相关
const loading = ref(false)
const total = ref(0)

const queryForm = ref({
  pageNum: 1,
  pageSize: 10
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const categoryFormRef = ref()

const categoryForm = ref({
  categoryName: '',
  parentId: 0,
  sortOrder: 0,
  isEnabled: 1
})

const formRules = {
  categoryName: [
    { required: true, message: '请输入类目名称', trigger: 'blur' }
  ],
  parentId: [
    { required: true, message: '请选择父级类目', trigger: 'change' }
  ]
}

// 树形组件配置
const defaultProps = {
  children: 'children',
  label: 'categoryName'
}

// 计算属性：获取一级类目列表
const firstLevelCategories = computed(() => {
  return categoryTreeData.value.filter(category => category.parentId === 0)
})

// 获取类目树形数据
const getCategoryTree = async () => {
  try {
    const result = await api.get('/tCategory/listAll1')
    if (result.code === 200) {
      const treeData = buildTree(result.data.list)
      categoryTreeData.value = treeData
      originalCategoryData.value = [...result.data.list] // 保存原始数据

      // 默认展开第一层
      if (categoryTreeData.value.length > 0) {
        defaultExpandedKeys.value = [categoryTreeData.value[0].id]
        // 默认选中"手机数码"类目
        nextTick(() => {
          const phoneCategory = findCategoryByName(categoryTreeData.value, '手机数码')
          if (phoneCategory) {
            selectedCategory.value = phoneCategory
            getSubcategoryList(phoneCategory.id)
          }
        })
      }
    } else {
      ElMessage.error(result.msg || '获取类目列表失败')
    }
  } catch (error) {
    ElMessage.error('请求失败')
  }
}

// 构建树形结构
const buildTree = (data) => {
  const map = {}
  const result = []

  // 初始化所有节点
  data.forEach(item => {
    map[item.id] = { ...item, children: [] }
  })

  // 构建父子关系
  data.forEach(item => {
    const node = map[item.id]
    if (item.parentId === 0 || !item.parentId) {
      result.push(node)
    } else {
      if (map[item.parentId]) {
        map[item.parentId].children.push(node)
      }
    }
  })

  return result
}

// 根据名称查找类目
const findCategoryByName = (categories, name) => {
  for (const category of categories) {
    if (category.categoryName === name) {
      return category
    }
    if (category.children && category.children.length > 0) {
      const found = findCategoryByName(category.children, name)
      if (found) return found
    }
  }
  return null
}

// 树节点点击事件
const handleNodeClick = (data) => {
  selectedCategory.value = data
  // 获取子类目列表
  getSubcategoryList(data.id)
}

// 获取子类目列表
const getSubcategoryList = async (parentId) => {
  loading.value = true
  try {
    const params = {
      pageNum: queryForm.value.pageNum,
      pageSize: queryForm.value.pageSize,
      parentId: parentId
    }

    const result = await api.get('/tCategory/listAll1', params)

    if (result.code === 200) {
      subcategoryList.value = result.data.list
      total.value = result.data.total
    } else {
      ElMessage.error(result.msg || '获取子类目列表失败')
    }
  } catch (error) {
    ElMessage.error('请求失败')
  } finally {
    loading.value = false
  }
}

// 新增一级类目
const handleAddRootCategory = () => {
  dialogTitle.value = '新增一级类目'
  isEdit.value = false
  categoryForm.value = {
    categoryName: '',
    parentId: 0,
    sortOrder: 0,
    isEnabled: 1
  }
  dialogVisible.value = true
}

// 新增子类目
const handleAddChildCategory = (parentCategory) => {
  dialogTitle.value = '新增子类目'
  isEdit.value = false
  categoryForm.value = {
    categoryName: '',
    parentId: parseInt(parentCategory.id),
    sortOrder: 0,
    isEnabled: 1
  }
  dialogVisible.value = true
}

// 编辑类目
const handleEditCategory = (category) => {
  dialogTitle.value = '编辑类目'
  isEdit.value = true
  categoryForm.value = {
    id: category.id,
    categoryName: category.categoryName,
    parentId: category.parentId,
    sortOrder: category.sortOrder,
    isEnabled: category.isEnabled
  }
  dialogVisible.value = true
}

// 删除类目
const handleDeleteCategory = (category) => {
  // 检查是否为一级类目且有子类目
  if (category.parentId === 0 && category.children && category.children.length > 0) {
    ElMessageBox.alert('该一级类目下存在子类目，请先删除所有子类目后再删除该类目', '提示', {
      type: 'warning'
    })
    return
  }

  ElMessageBox.confirm(
      `确定要删除类目"${category.categoryName}"吗？删除后将无法恢复。`,
      '删除确认',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
  ).then(async () => {
    try {
      const result = await api.postJson('/tCategory/delete', [category.id])
      if (result.code === 200) {
        ElMessage.success('删除成功')
        // 重新加载数据
        await getCategoryTree()
        // 如果删除的是当前选中的类目，清空选中项
        if (selectedCategory.value && selectedCategory.value.id === category.id) {
          selectedCategory.value = null
        }
        // 如果还有选中的类目，重新加载子类目列表
        if (selectedCategory.value) {
          await getSubcategoryList(selectedCategory.value.id)
        }
      } else {
        ElMessage.error(result.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 提交表单
const submitForm = async () => {
  categoryFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let result
        if (isEdit.value) {
          // 编辑类目
          result = await api.putJson('/tCategory/update', categoryForm.value)
        } else {
          // 新增类目
          result = await api.postJson('/tCategory/add', categoryForm.value)
        }

        if (result.code === 200) {
          ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
          dialogVisible.value = false
          // 重新加载数据
          await getCategoryTree()
          if (selectedCategory.value) {
            await getSubcategoryList(selectedCategory.value.id)
          }
        } else {
          ElMessage.error(result.msg || (isEdit.value ? '编辑失败' : '新增失败'))
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? '编辑失败' : '新增失败')
      }
    }
  })
}

// 取消对话框
const cancelDialog = () => {
  dialogVisible.value = false
}

// 分页相关方法
const handleSizeChange = (val) => {
  queryForm.value.pageSize = val
  if (selectedCategory.value) {
    getSubcategoryList(selectedCategory.value.id)
  }
}

const handleCurrentChange = (val) => {
  queryForm.value.pageNum = val
  if (selectedCategory.value) {
    getSubcategoryList(selectedCategory.value.id)
  }
}

// 搜索功能
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    // 如果搜索关键词为空，重新加载完整数据
    getCategoryTree()
    return
  }

  // 过滤树形数据
  filterTreeData(searchKeyword.value.trim())

  // 展开所有节点以便查看搜索结果
  nextTick(() => {
    if (categoryTreeRef.value) {
      categoryTreeRef.value.store._getAllNodes().forEach(node => {
        node.expand()
      })
    }

    // 自动选中第一个匹配项并展示详情
    selectFirstMatchedNode()
  })
}

// 过滤树形数据
const filterTreeData = (keyword) => {
  // 基于原始完整数据构建树结构
  const fullTreeData = buildTree(originalCategoryData.value)

  const filterNode = (node) => {
    // 检查当前节点是否匹配关键词
    const isMatch = node.categoryName.toLowerCase().includes(keyword.toLowerCase())

    // 递归检查子节点
    let hasMatchedChildren = false
    if (node.children && node.children.length > 0) {
      const filteredChildren = node.children
          .map(child => filterNode(child))
          .filter(child => child !== null)

      if (filteredChildren.length > 0) {
        hasMatchedChildren = true
        return {
          ...node,
          children: filteredChildren
        }
      }
    }

    // 如果当前节点匹配或者有匹配的子节点，则返回该节点
    if (isMatch || hasMatchedChildren) {
      return node
    }

    return null
  }

  // 遍历所有根节点进行过滤
  const filteredData = fullTreeData
      .map(node => filterNode(node))
      .filter(node => node !== null)

  categoryTreeData.value = filteredData
}

// 选中第一个匹配的节点
const selectFirstMatchedNode = () => {
  const findFirstNode = (nodes) => {
    for (const node of nodes) {
      if (node) {
        return node
      }
      if (node.children && node.children.length > 0) {
        const childResult = findFirstNode(node.children)
        if (childResult) {
          return childResult
        }
      }
    }
    return null
  }

  // 查找第一个匹配的节点
  const firstNode = findFirstNode(categoryTreeData.value)

  if (firstNode) {
    // 自动选中第一个节点
    selectedCategory.value = firstNode
    // 获取该节点的子类目列表
    getSubcategoryList(firstNode.id)

    // 在树中高亮显示该节点
    nextTick(() => {
      if (categoryTreeRef.value) {
        categoryTreeRef.value.setCurrentKey(firstNode.id)
      }
    })
  } else {
    // 如果没有匹配项，清空选中项
    selectedCategory.value = null
    subcategoryList.value = []
  }
}

// 初始化
onMounted(() => {
  getCategoryTree()
})
</script>

<style scoped>.category-tree-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  height: calc(100vh - 120px);
  overflow-y: auto;
}

.category-tree-container .header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.category-tree-container .header h3 {
  margin: 0;
}

.search-box {
  margin-bottom: 15px;
}

.category-detail-container {
  height: calc(100vh - 120px);
  overflow-y: auto;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.empty-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.category-table-container {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.table-header {
  margin-bottom: 15px;
}

.table-header h3 {
  margin: 0;
}

.category-info {
  padding: 20px 0;
}
</style>1